<link rel="stylesheet" href="../public/all/css/zTreeStyle/zTreeStyle.css" type="text/css">
<script type="text/javascript" src="../public/all/js/jquery.ztree.all.min.js"></script>
<style type="text/css">
	.tree {
		border: 1px solid #000;
		border-radius: 5px;
	}
	.clue { line-height: 40px; }
</style>

<div class="filter">
    <div class="f1 item" style="width: 70px; line-height: 30px;">
       请选择角色
    </div>
    <div class="f5 item" style="width: 200px;">
        <select data-am-selected>
        </select>
    </div>
    <div class="clear"></div>
</div>

<div class="clue red">【操作提示】每设置完一个角色权限，请即刻保存。</div>
<div class="tree"><ul id="tree" class="ztree"></ul></div>

<div class="button_line">
    <button class="am-btn am-btn-primary btn-save admin_button">保存</button>
</div>

<script>
	var map = {};
	Classify.queryExt("roles", "idname", true, {}, function(r) {
        for (var i in r) {
			if (parseInt(i) < 50) continue;
			map[i] = r[i];
		}

		// 填充角色
		var s = $(".f5 select");
		s.empty();
		for (var i in map) {
			s.append('<option value="' + i + '">' + map[i] + '</option>');
		}
		fillTrees();
    });

	// 生成树
    var setting = {
		check: {
			enable: true,
		},
		data: {
			simpleData: {
				enable: true
			}
		}
	};
	var code;
	function setCheck() {
		var zTree = $.fn.zTree.getZTreeObj("tree"),
			py = "p",
			sy = "s",
			pn = "p",
			sn = "s",
		type = { "Y":py + sy, "N":pn + sn };
		zTree.setting.check.chkboxType = type;
	}
	function fillTrees() {
		var grade = $(".f5 select").val();
		var zNodes = Rights.tree(grade);
		$(document).ready(function(){
			$.fn.zTree.init($("#tree"), setting, zNodes);
			setCheck();
		});
	}
	
	// 取得所有被选中的权限
	function queryRights() {
		var rights = [];
		var arr = $.fn.zTree.getZTreeObj("tree").getCheckedNodes(true);
		for (var i in arr) {
			if (!arr[i].cmd) continue;
			var arr2 = arr[i].cmd.split(",");
			for (var j in arr2)
				rights.push(arr2[j]);
		}
		
		var arr = ["/user/online/query", "/classify/save", "/classify/refresh", ];
		for (var i in arr) rights.push(arr[i]);
		return rights;
	}

	$(".f5 select").change(fillTrees);

	// 保存权限
	$(".btn-save").click(function() {
		var m = queryRights();
		Rights.save($(".f5 select").val(), m);
	});
</script>